package com.tuananh.radnom.model.netpoller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorValue;
import org.rrd4j.core.RrdDb;
import org.rrd4j.core.RrdDef;
import org.rrd4j.core.Sample;

import com.tuananh.radnom.model.NetInterface;
import com.tuananh.radnom.model.netservice.NetService;

@XmlDiscriminatorValue("default-rrd")
public class DefaultRRD extends RadnomRRD {

	@Override
	public void updateRRD(PollInfo pollInfo, Object result) {
		// TODO Auto-generated method stub
		NetService netService = pollInfo.getNetService();
		NetInterface netInt = pollInfo.getNetInt();

		File file = new File("../rrd/" + netInt.getName() + "."
				+ netService.getName() + ".rrd");
		if (!file.exists()) {

			try {
				RrdDef rrdef = new RrdDef("../rrd/" + netInt.getName() + "."
						+ netService.getName() + ".rrd");
				rrdef.setStartTime(new Date().getTime() / 1000);

				rrdef.setStep(this.step);
				for (String ds : this.ds) {
					rrdef.addDatasource("DS:" + ds);
				}
				for (String rra : this.rra) {
					rrdef.addArchive("RRA:" + rra);
				}
				RrdDb rrdDb = new RrdDb(rrdef);

				rrdDb.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			HashMap<String, String> valueMap = (HashMap<String, String>) result;
			RrdDb rrdDb = new RrdDb("../rrd/" + netInt.getName() + "."
					+ netService.getName() + ".rrd");
			
			Sample sample = rrdDb.createSample();
			String updateStr = new Date().getTime() / 1000 + "";
			for (String ds : this.ds) {
				String dsVariable = ds.substring(0, ds.indexOf(":"));
				updateStr += ":" + valueMap.get(dsVariable).trim();
			}
			sample.setAndUpdate(updateStr);
			rrdDb.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
